package com.lvtu.monitor.dao.base;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * @Title: BaseDaoTemplate.java
 * @Package com.lvtu.monitor.dao.base
 * @Description: TODO
 * @author dengcheng
 * @date 2015-5-25 下午4:09:29
 * @version V1.0.0
 */
@Repository
public class BaseDaoTemplate implements AbstractRepository {

	@Autowired
	private MongoTemplate mongoTemplate;

	public void insert(Object obj) {
		mongoTemplate.insert(obj);
	}

	public <T> T findOne(String id, Class<T> clazz) {
		// TODO Auto-generated method stub
		return mongoTemplate.findOne(
				new Query().addCriteria(Criteria.where("_id").is(id)), clazz);
	}

	public <T> List<T> findAll(Class<T> clazz) {
		// TODO Auto-generated method stub
		return (List<T>) mongoTemplate.find(new Query(), clazz);
	}

	public <T> void removeOne(String id, Class<T> clazz) {
		Criteria criteria = Criteria.where("_id").in(id);
		if (criteria != null) {
			Query query = new Query(criteria);
			mongoTemplate.remove(mongoTemplate.findOne(query, clazz));
		}
	}

	@Override
	public <T> void batchInsert(List<Class<T>> list, Class<T> clazz) {
		// TODO Auto-generated method stub
		mongoTemplate.insert(list, clazz);
	}

	@Override
	public <T> void updateOne(String id, Map<String, Object> updates, Class<T> clazz) {
		
		Criteria criteria = Criteria.where("_id").in(id);
		Query query = new Query(criteria);
		Update update = new Update();
		for (String field : updates.keySet()) {
			update.set(field, updates.get(field));
		}
		mongoTemplate.updateFirst(query, update, clazz);
	}
}
